/*
Reverse Words in a String Total Accepted: 68523 Total Submissions: 453349 My Submissions Question Solution
Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string
*/

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <fstream>
#include <sstream>
#include <unordered_set>
#include "print.h"
using namespace std;

/**
* Definition for binary tree*/


void testForStack()
{
	stack<int> mystack;
	mystack.push(10);
	mystack.push(20);
	mystack.top() -= 5;
	cout << "mystack.top() is now " << mystack.top() << endl;
}

void testForIntToString()
{
	int a = 10;
	stringstream ss;
	ss << a;
	string str = ss.str();
	cout << str << endl;

	string str1 = to_string(a);

}


class Solution {
public:
	void reverseWords(string &s) {
		if (s.size() ==0)
		{
			return;
		}
		if (s.size()==1&& s[0]==' ')
		{
			s.clear();
			return;
		}

		stack<string> wordStack;
		
		int begin, end;
		begin = 0;
		end = 0;

		int size = s.size();
		while (end <size)
		{
			while (s[begin] == ' '&&begin!=size)
			{
				begin++;
			}
			if (begin == size)
			{ 
				end =size;
				break;
			}
			end = begin;
			while (s[end] != ' '&&end!=size)
			{
				end++;
			}

			wordStack.push(s.substr(begin,end-begin));
			begin = end;
		}
		if (wordStack.empty())
		{
			s.clear();
			return;
		}

		string str = wordStack.top();
		wordStack.pop();
		while (!wordStack.empty())
		{
			str = str + " " + wordStack.top();
			wordStack.pop();
		}
		s.clear();

		s = str;
	}
};

int main(int argc, char* argv[])
{

	




	string str = "the sky is blue";

	

	//strVec.push_back("3");
	//strVec.push_back("*");


	int result;
	Solution s;
    s.reverseWords(str);
	//cout << "The result is : " << result << endl;
	//result = s.partition(str);
	//stackTree.push(p->left);
	//stackTree.push(p->right);
	//if (s.isPalindrome(str1))
	//	cout << " True" << endl;
	//else
	//	cout << "false" << endl;
	system("pause");
	return 0;
}
//std::unordered_set<std::string> myset =
//{ "hot", "dot", "dog", "lot", "log" };

//std::cout << "myset contains:";
// for (auto it = myset.begin(); it != myset.end(); ++it)
//std::cout << " " << *it;
//;; std::cout << std::endl;

//TreeNode *root = new TreeNode(1);
//TreeNode *left = new TreeNode(2);
//TreeNode *right = new TreeNode(3);

//root->left = left;
//root->right = right;